package interceptor;

import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

import dto.Dto;
import services.impl.RedisService;
import services.impl.TokenServiceImpl;

public class AuthInterceptor implements Interceptor{
	
	@Inject
	TokenServiceImpl tokenService;
	
	@Override
	public void intercept(Invocation inv) {
		System.out.println("Before method invoking check the user authorization");
		// check the authorization
		int userId = checkAuth(inv);
		if(userId>0){
			System.out.println("Authorization pass");
			inv.getController().getRequest().setAttribute("userId", userId);
			inv.invoke();
			System.out.println("After method invoking");
		}else{
			System.out.println("Method not invoking, return directly");
			Dto dto = new Dto();
			dto.setErrMsg("Authorization failed. Access denied.");
			inv.getController().renderJson(Dto.getFinalDto(dto));
		}
	}
	
	private int checkAuth(Invocation inv){
//		String json = inv.getController().getRawData();
		String token = inv.getController().getRequest().getHeader("Authorization");
		return tokenService.checkToken(token, new RedisService());
	}
}
